﻿/* ===============================================================================  
 * Copyright (c) 2010 Acid Frameworks
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 * =============================================================================== */

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;

///////////////////////////////////////////////
// TODO : Handle Disconnect and Timeouts. 
///////////////////////////////////////////////
namespace Acid.Network.Tcp
{
    public delegate void OnConnected (Server listener, Client client);
    public delegate void OnDisconnect(Server listener, Client client);
    
    /// <summary>
    /// Tcp Server Class. Handles incoming Connections and managing a group of connected clients.
    /// </summary>
    public class Server : IDisposable
    {
        private int                    port;
        private TcpListener            listener;
        private Thread                 acceptThread;
        private Thread                 validateThread;
        private List<Client>           clients;
        private bool                   running;
        private int                    bufferSize;
        public event OnConnected       OnClientConnect;
        public event OnDisconnect      OnClientDisconnect;
        public event OnPacket          OnPacket;
        public event OnError           OnError;
        
        #region Constructors

        /// <summary>
        /// Creates a new Server object. Default buffer size of 1024.
        /// </summary>
        /// <param name="port">The port this Server should start listening for incoming connections.</param>
        public Server(int port) : this(port, 1024) { }
       
        /// <summary>
        /// Creates a new Server object.
        /// </summary>
        /// <param name="port">The port this Server should start listening for incoming connections.</param>
        /// <param name="bufferSize">The size of the Buffer. Connecting clients will need to have this same buffer size</param>
        public Server(int port, int bufferSize)
        {
            this.port = port;

            this.bufferSize = bufferSize;

            this.clients = new List<Client>();
        }

        #endregion

        #region Properties

        /// <summary>
        /// A Collection of current connected|active clients.
        /// </summary>
        public List<Client> Clients
        {
            get
            {
                return this.clients;
            }
        }
       
        /// <summary>
        /// Is this server running.
        /// </summary>
        public bool Started
        {
            get { return this.running; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Starts the server. Once started, the server will start accepting incoming client connections.
        /// </summary>
        public void Start     ()
        {
            this.listener = new TcpListener(IPAddress.Parse("127.0.0.1"), this.port);

            this.listener.Start();
            
            this.running      = true;

            this.acceptThread = new Thread(new ThreadStart(this.AcceptThread));

            this.acceptThread.Start();

            this.validateThread = new Thread(new ThreadStart(this.ValidateThread));

            this.validateThread.Start();
        }
        
        /// <summary>
        /// Stops the Server. Essentially the same as Dispose().
        /// </summary>
        public void Stop      ()
        {
            this.Dispose(true);
        }

        /// <summary>
        /// Broadcasts a Packet to all connected clients.
        /// </summary>
        /// <param name="packet"></param>
        public void Broadcast (Packet packet)
        {
            lock (this.clients)
            {
                for (int i = 0; i < this.clients.Count; i++)
                {
                    clients[i].Send(packet);
                }
            }
        }
       
        /// <summary>
        /// Sends a Packet to a single Client.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="packet"></param>
        public void Send      (Client client, Packet packet)
        {
            client.Send(packet);
        }

        #endregion

        #region Threads

        private void AcceptThread   ()
        {
            while (this.running)
            {
                try
                {
                    TcpClient _client = this.listener.AcceptTcpClient();

                    Client client = new Client(_client, this.bufferSize);

                    client.OnPacket += new OnPacket(this.ClientOnPacket);

                    client.OnError  += new OnError(this.ClientOnError);

                    this.clients.Add(client);

                    if (this.OnClientConnect != null)
                    {
                        this.OnClientConnect(this, client);
                    }
                }
                catch
                {
                    // No Problem
                }
            }
        }
 

        private void ValidateThread ()
        {
            while (this.running)
            {
                Thread.Sleep(1000);

                foreach (Client client in clients)
                {
                    client.Send(new Packet("_ping_"));
                }
            }
        }

        #endregion

        #region Events

        private void ClientOnPacket(Client client, Packet packet)
        {
            if (packet.ID.Contains("_close_"))
            {
                this.clients.Remove(client);

                if (this.OnClientDisconnect != null)
                {
                    this.OnClientDisconnect(this, client);
                }
            }
            else
            {
                if (this.OnPacket != null)
                {
                    this.OnPacket(client, packet);
                }
            }
        }

        private void ClientOnError(Client client, string message)
        {
            if (this.OnError != null)
            {
                this.OnError(client, message);
            }
        }

        #endregion

        #region IDisposable Members

        private bool disposed = false;

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!disposed)
                {
                    this.running = false;

                    this.acceptThread.Abort();

                    this.validateThread.Abort();

                    this.listener.Stop();

                    foreach (Client client in clients)
                    {
                        client.Dispose();
                    }
                    
                }

                this.disposed = true;
            }
        }

        /// <summary>
        /// Disposes this Server and its connections. Also aborts all active threads.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
        }

        ~Server()
        {
            this.Dispose(false);
        }

        #endregion
    }
}
